package com.zidian.study.activity;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.student.trucks.R;
import com.zidian.study.event.LotteryNumberChangeEvent;
import com.zidian.study.globa.Constant;
import com.zidian.study.globa.ToolBarActivity;
import com.zidian.study.utils.GetUserInfo;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by GongCheng on 2016/12/7.
 */

public class TreasureActivity extends ToolBarActivity {
    @Bind(R.id.treasure_chests_top)
    ImageView treasureChestsTop;
    @Bind(R.id.lottery_number)
    TextView lotteryNumberTv;
    @Bind(R.id.toolbar_sumbit)
    TextView toolbarRight;
    //奖品等级
    private static final String[] PRIZE_LEVEL = {"S级礼物", "A级礼物", "B级礼物", "C级礼物", "D级礼物"};
    private static final String[] PRIZE_PRICE = {"价值5000-6000元", "价值1000元", "价值400元", "价值100元", "价值60元"};

    private AnimationDrawable animationDrawable;
    StaticHandler handler = new StaticHandler(this);

    private PopupWindow awardPopupWindow;
    private PopupWindow noAwardPopupWindow;
    private int lotteryNumber;
    private int prizeLevel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_evaluate_tags);
        setContentView(R.layout.activity_treasure);
        ButterKnife.bind(this);
        setTitle("我的宝箱");
        toolbarRight.setText("中奖记录");
        animationDrawable = (AnimationDrawable) this.getResources().getDrawable(R.drawable.anim_treasure_chest);
        treasureChestsTop.setImageDrawable(animationDrawable);
        lotteryNumber = getIntent().getIntExtra("lotteryNumber", 0);
        lotteryNumberTv.setText("共有" + lotteryNumber + "次机会");
    }

    /**
     * 查看中奖记录
     */
    @OnClick(R.id.toolbar_sumbit)
    public void prizeRecord() {
        startActivity(PrizeRecordActivity.class);
    }

    /**
     * 点击打开宝箱
     */
    @OnClick(R.id.treasure_chests_top)
    public void openTreasureChest() {
        if (lotteryNumber > 0) {
            animationDrawable.start();
            lottery();
        } else {
            Snackbar.make(lotteryNumberTv, "对不起您没有抽奖机会", Snackbar.LENGTH_SHORT).show();
        }
    }

    /**
     * 静态内部类handler
     */
    static class StaticHandler extends Handler {
        WeakReference<TreasureActivity> activityWeakReference;

        StaticHandler(TreasureActivity activity) {
            activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            TreasureActivity activity = activityWeakReference.get();
            super.handleMessage(msg);
            if (activity != null) {
                switch (msg.what) {
                    //无奖品
                    case 0:
                        activity.animationDrawable.stop();
                        activity.showNoAwardPopUpWindow();
                        break;
                    //有奖品
                    case 1:
                        activity.animationDrawable.stop();
                        activity.showAwardPopUpWindow();
                        break;
                }
            }
        }
    }

    /**
     * 抽到奖品
     */
    private void showAwardPopUpWindow() {
        FrameLayout animateView;
        ImageView cancelIv;
        TextView sureTv;
        TextView prizepriceTv;
        TextView prizeTv;
        TextView redeemTimeTv;
        TextView redeemPlaceTv;
        View view = LayoutInflater.from(this).inflate(R.layout.has_award_popupwindow, null);
        cancelIv = (ImageView) view.findViewById(R.id.cancel);
        sureTv = (TextView) view.findViewById(R.id.sure);
        prizepriceTv = (TextView) view.findViewById(R.id.prize_price_tv);
        prizeTv = (TextView) view.findViewById(R.id.prize_tv);
        animateView = (FrameLayout) view.findViewById(R.id.animate_view);
        prizepriceTv.setText("获得" + PRIZE_PRICE[prizeLevel - 1] +"的奖品");
        prizeTv.setText(PRIZE_LEVEL[prizeLevel - 1]);
        cancelIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                awardPopupWindow.dismiss();
            }
        });
        sureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                awardPopupWindow.dismiss();
            }
        });
        if (awardPopupWindow == null) {
            awardPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        }
        awardPopupWindow.setAnimationStyle(R.style.PopupAnimaFade);
        awardPopupWindow.showAtLocation(treasureChestsTop, Gravity.CENTER, 0, 0);
        //设置动画
        Animation scaleAnimation = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f
        );
        scaleAnimation.setDuration(300);
        scaleAnimation.setInterpolator(new AccelerateInterpolator());
        scaleAnimation.setFillEnabled(true);
        scaleAnimation.setFillAfter(true);
        animateView.startAnimation(scaleAnimation);

    }

    /**
     * 没有抽到奖品
     */
    private void showNoAwardPopUpWindow() {
        ImageView cancelIv;
        TextView sureTv;
        FrameLayout animateView;

        View view = LayoutInflater.from(this).inflate(R.layout.no_award_popupwindow, null);
        cancelIv = (ImageView) view.findViewById(R.id.cancel);
        sureTv = (TextView) view.findViewById(R.id.sure);
        animateView = (FrameLayout) view.findViewById(R.id.animate_view);
        cancelIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noAwardPopupWindow.dismiss();
            }
        });
        sureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noAwardPopupWindow.dismiss();
            }
        });
        if (noAwardPopupWindow == null) {
            noAwardPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        }
        noAwardPopupWindow.setAnimationStyle(R.style.PopupAnimaFade);
        //设置动画
        Animation scaleAnimation = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f
        );
        scaleAnimation.setDuration(300);
        scaleAnimation.setInterpolator(new AccelerateInterpolator());
        scaleAnimation.setFillEnabled(true);
        scaleAnimation.setFillAfter(true);
        noAwardPopupWindow.showAtLocation(treasureChestsTop, Gravity.CENTER, 0, 0);
        animateView.startAnimation(scaleAnimation);

    }

    public void lottery() {
        String url = Constant.URL_GOAL + "winnersPrize/add";
        Map<String, String> map = new HashMap<>();
        map.put("token", GetUserInfo.getToken(context));
        map.put("studentId", GetUserInfo.getStudentId(context));
        OkHttpUtils.post().url(url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Snackbar.make(treasureChestsTop, e.getMessage(), Snackbar.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt("code");
                    switch (code) {
                        case 200: //中奖
                            response.toString();
                            lotteryNumberTv.setText("共有" + jsonObject.getInt("lotteryNumber") + "次机会");
                            EventBus.getDefault().post(new LotteryNumberChangeEvent(jsonObject.getInt("lotteryNumber")));
                            int num = jsonObject.getInt("num");
                            prizeLevel = num;
                            handler.sendEmptyMessageDelayed(1, 1000);
                            break;
                        case 201: //没有此学生
                            break;
                        case 202: //没有中奖
                            lotteryNumberTv.setText("共有" + jsonObject.getInt("lotteryNumber") + "次机会");
                            EventBus.getDefault().post(new LotteryNumberChangeEvent(jsonObject.getInt("lotteryNumber")));
                            handler.sendEmptyMessageDelayed(0, 1000);
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
